import 'dart:async';
import 'dart:io';

import 'package:distribution_mall_flutter/base/base_service.dart';
import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/http/modules/common.dart';
import 'package:distribution_mall_flutter/pages/home/domain/home_entity.dart';
import 'package:distribution_mall_flutter/pages/home/home_provider.dart';
import 'package:distribution_mall_flutter/utils/common_third.dart';
import 'package:distribution_mall_flutter/utils/log.dart';
import 'package:distribution_mall_flutter/utils/storage.dart';
import 'package:distribution_mall_flutter/utils/utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:url_launcher/url_launcher.dart';

part 'home_service.g.dart';

class HomeService extends BaseService {
  HomeService(super.ref);

  @override
  onReady() {
    if (kIsWeb) return;
    queryAppInfo();
  }

  // 获取 apollo 设置的 app相关信息
  Future<void> queryAppInfo() async {
    AppInfoEntity? data = await CommonApi.getAppInfo({});
    bool isGooglePlayPackage = await Utils.isGooglePlayPackage();
    String? cancelVersion =
        EPstorage.deviceInfo.get(DeviceInfoBoxKey.cancelVersionNumber);
    int? cancelPatch =
        EPstorage.deviceInfo.get(DeviceInfoBoxKey.cancelPatchNumber);
    int? patchNumber;
    if (Platform.isAndroid || Platform.isIOS) {
      bool showPatchUpdate = false;

      try {
        patchNumber = await shorebirdCodePush.currentPatchNumber();
        EPstorage.deviceInfo.put(DeviceInfoBoxKey.patchNumber, patchNumber);
        showPatchUpdate =
            await shorebirdCodePush.isNewPatchAvailableForDownload();
      } catch (e) {}

      String curVersion = getIt<PackageInfo>().version;
      bool showVersionUpdatre = false;
      bool hideCancel = false;

      String? s = data?.hardList?.firstWhere(
          (item) => item.compareTo(curVersion) > 0,
          orElse: () => '');

      // 是否隐藏 取消按钮
      if ((s != null && s.isNotEmpty) || data?.force == true) {
        hideCancel = true;
      }

      String titleVersion = '', version = '';
      // 判断当前app版本是否需要更新
      if (Platform.isIOS && data?.iosVersionV2 != null) {
        version = data?.iosVersionV2 ?? '';
        showVersionUpdatre = curVersion.compareTo(data?.iosVersionV2 ?? '') < 0;
      } else if (isGooglePlayPackage && data?.googleVersion != null) {
        version = data?.googleVersion ?? '';
        showVersionUpdatre =
            curVersion.compareTo(data?.googleVersion ?? '') < 0;
      } else if (!isGooglePlayPackage || data?.appVersionNoV2 != null) {
        version = data?.appVersionNoV2 ?? '';
        showVersionUpdatre =
            curVersion.compareTo(data?.appVersionNoV2 ?? '') < 0;
      }

      // 2024.08.23
      // 需要热更的版本，只能用于 204（包括）以上版本
      if (showPatchUpdate &&
          !(data?.updatePatchList?.isNotEmpty == true &&
              data?.updatePatchList?.contains(curVersion) == true)) {
        // 如果不是 测试 模式，版本 补丁 不符合，则直接 false
        showPatchUpdate = false;
      }

      // 开启测试模式
      if (data?.isTest == true) {
        String? id = EPstorage.userInfo.get(UserInfoBoxKey.id);
        // 开启测试模式后，不符合 白名单 用户 全部禁用更新
        if (!(data?.userWhiteList?.isNotEmpty == true &&
            id?.isNotEmpty == true &&
            data?.userWhiteList?.contains(id) == true)) {
          showVersionUpdatre = false;
          showPatchUpdate = false;
        }
      }

      // 不为null，则代表取消过 更新版本内容，不在显示更新提示
      if (cancelVersion != null && cancelVersion == version) {
        showVersionUpdatre = false;
        // 不为null，则代表取消过 更新补丁 内容，不在显示更新提示
        if (cancelPatch != null && cancelPatch == patchNumber) {
          showPatchUpdate = false;
        }
      }

      // 如果 缓存的版本号 与 需要更新的版本相同，则自动设为 false
      if (showPatchUpdate &&
          cancelPatch != null &&
          cancelPatch == patchNumber) {
        showPatchUpdate = false;
      }

      String confirmText = S.current.update_now;
      // 跳转 按钮的文案
      if (data?.onlySkipApkMallUrl != true && showVersionUpdatre) {
        if (Platform.isIOS) {
          confirmText = 'Go To Apple';
        } else if (isGooglePlayPackage) {
          confirmText = 'Go To Google';
        }
      } else if (showVersionUpdatre) {
        confirmText = 'Go Download';
      }

      ref.read(appInfoProvider.notifier).setConfirmText(confirmText);

      titleVersion =
          '$version${patchNumber == null ? '' : '.'}${int.tryParse('$patchNumber') ?? ''}';
      String curTitleVersion =
          '$version${cancelPatch == null ? '' : '.'}${int.tryParse('$cancelPatch') ?? ''}';
      ref.read(appInfoProvider.notifier).setData(data, showVersionUpdatre,
          showPatchUpdate, hideCancel, titleVersion, version, curTitleVersion);
    }
  }

  // 设置本地存储，用于 用户点击取消后，当前版本不再给予提示，故 “谨慎” 设置
  cancel() {
    ref.read(appInfoProvider.notifier).setCanPop(true);
    final appInfoModal = ref.watch(appInfoProvider);
    if (appInfoModal.showPatchUpdate) {
      setPatchNumber();
      EPstorage.deviceInfo
          .put(DeviceInfoBoxKey.cancelVersionNumber, appInfoModal.version);
      return;
    }
    if (appInfoModal.showVersionUpdate) {
      EPstorage.deviceInfo
          .put(DeviceInfoBoxKey.cancelVersionNumber, appInfoModal.version);
      // EPstorage.deviceInfo.put(DeviceInfoBoxKey.cancelPatchNumber, null);
    }
  }

  setPatchNumber() {
    int? curPatchNumber =
        EPstorage.deviceInfo.get(DeviceInfoBoxKey.patchNumber);
    EPstorage.deviceInfo
        .put(DeviceInfoBoxKey.cancelPatchNumber, curPatchNumber);
  }

  confirm() async {
    final appInfoModal = ref.watch(appInfoProvider);
    bool isGooglePlayPackage = await Utils.isGooglePlayPackage();

    if (appInfoModal.showVersionUpdate) {
      String? str = appInfoModal.data?.apkMallUrl;
      if (appInfoModal.data?.onlySkipApkMallUrl != true) {
        if (isGooglePlayPackage) {
          str = appInfoModal.data?.googleMallUrl;
        } else if (Platform.isIOS) {
          str = appInfoModal.data?.iosMallUrl;
        }
      }
      Uri url = Uri.parse(str ?? '');
      if (await canLaunchUrl(url)) {
        await launchUrl(url, mode: LaunchMode.externalApplication);
      }
      return;
    }
    ref.read(appInfoProvider.notifier).setCanPop(true);
    if (appInfoModal.showPatchUpdate) {
      ref.read(appInfoProvider.notifier).setUpdating(true);
      shorebirdCodePush.downloadUpdateIfAvailable().then((_) {
        setPatchNumber();

        EPToast.showToast(S.current.update_successfully);
      }).whenComplete(() {
        // appRouter.maybePop(true);
        SmartDialog.dismiss();
        cancel();
      });
    }
  }
}

@riverpod
HomeService homeService(HomeServiceRef ref) {
  return HomeService(ref);
}
